using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace WPCoco
{
    /// <summary>
    /// Custom SpriteBatch used by the engine for keep a cache for reuse 
    /// </summary>
    public class CachedSpriteBatch : SpriteBatch
    {
        public CachedSpriteBatch(GraphicsDevice graphicsDevice)
            : base(graphicsDevice)
        {
            RetainCount = 0;   
        }

        int RetainCount;

        /// <summary>
        /// Hold the reference for keeping using it, increase in one the RetainCount
        /// </summary>
        public void Retain() 
        {
            RetainCount++;
        }

        /// <summary>
        /// Decrement RetainCount, if it is less or equal than 0 then release it for reuse
        /// </summary>
        public void Release() 
        {
            RetainCount--;
            CheckOwnership();
        }

        void CheckOwnership() 
        {
            if (RetainCount <= 0)
            {
                RetainCount = 0;
                SpriteBatchCache.Restore(this);
            }
        }

        public new void End()
        {
            base.End();
            CheckOwnership();
        }

    }
}
